package com.hiwan.unions.view.popupWindow;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;

import com.hiwan.unions.R;
import com.hiwan.unions.util.CheckUtils;
import com.pl.wheelview.WheelView;
import com.yanzhenjie.nohttp.Logger;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by llg on 2017/7/9.
 */
public class DatePop extends PopupWindow {
    private Activity activity;
    private View conentView;
    public OnTextLinstener cardListener;
    private WheelView year, month, day;
    int curYear;
    int curMonth;
    int curDate;
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
    SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
    SimpleDateFormat dayFormat = new SimpleDateFormat("dd");

    public DatePop(final Activity context) {
        this.activity = context;
        DisplayMetrics dm = new DisplayMetrics();
        //获取屏幕信息
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        conentView = inflater.inflate(R.layout.popwindow_date, null);
        // 设置SelectPicPopupWindow的View
        this.setContentView(conentView);
        // 设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        // 设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        // 设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        // 刷新状态
        this.update();
        //设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(new BitmapDrawable());
        this.setAnimationStyle(R.style.mypopwindow_anim_style);
        this.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        conentView.setFocusable(true);
        conentView.setFocusableInTouchMode(true);
        conentView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK)
                    dismiss();
                return false;
            }
        });
        this.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams params = activity.getWindow().getAttributes();
                params.alpha = 1f;
                activity.getWindow().setAttributes(params);
            }
        });
        Calendar c = Calendar.getInstance();
        curYear = c.get(Calendar.YEAR);
        curMonth = c.get(Calendar.MONTH) + 1;//通过Calendar算出的月数要+1
        curDate = c.get(Calendar.DATE);
        year = findView(conentView, R.id.year);
        year.setData(initYear());
        year.setCyclic(false);
        year.setDefault(curYear - 1950);
        year.setOnSelectListener(new WheelView.OnSelectListener() {
            @Override
            public void endSelect(int id, String text) {
                Logger.i("执行   " + id);
                curYear = id + 1950;
                day.refreshData(initDay(curYear, curMonth));
                daySet(curDate, getDay(curYear, curMonth + 1));
            }

            @Override
            public void selecting(int id, String text) {
            }
        });

        month = findView(conentView, R.id.month);
        month.setData(initMonth());
        month.setCyclic(false);
        month.setDefault(curMonth - 1);
        month.setOnSelectListener(new WheelView.OnSelectListener() {
            @Override
            public void endSelect(int id, String text) {
                curMonth = id + 1;
                day.refreshData(initDay(curYear, curMonth));
                daySet(curDate, getDay(curYear, curMonth));
            }

            @Override
            public void selecting(int id, String text) {
            }
        });
        day = findView(conentView, R.id.day);
        day.setData(initDay(curYear, curMonth));
        day.setCyclic(false);
        day.setDefault(curDate - 1);
        day.setOnSelectListener(new WheelView.OnSelectListener() {
            @Override
            public void endSelect(int id, String text) {
                curDate = id + 1;
            }

            @Override
            public void selecting(int id, String text) {
            }
        });

        findView(conentView, R.id.disms).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        findView(conentView, R.id.custom).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Logger.i("curYear  " + curYear + "-" + curMonth + "+" + curDate);
                cardListener.OnDateText(curYear, dayString(curMonth), dayString(curDate));
                dismiss();
            }
        });
    }

    private String dayString(int i) {
        if (i < 10) {
            return "0" + i;
        }
        return i + "";
    }

    private void daySet(int i, int z) {
        if (i > z) {
            curDate = z;
            day.setDefault(curDate - 1);
        }
    }

    public <T extends View> T findView(View view, int viewId) {
        return (T) view.findViewById(viewId);
    }

    /**
     * 初始化年
     */
    private ArrayList<String> initYear() {
        ArrayList<String> strings = new ArrayList<String>();
        for (int i = 1950; i < 2060; i++) {
            strings.add(i + "年");
        }
        return strings;
    }

    /**
     * 初始月
     */
    private ArrayList<String> initMonth() {
        ArrayList<String> strings = new ArrayList<String>();
        for (int i = 1; i < 13; i++) {
            if (i < 10) {
                strings.add("0" + i + "月");
            } else {
                strings.add(i + "月");
            }
        }
        return strings;
    }

    /**
     * 初始日
     */
    private ArrayList<String> initDay(int curYear, int curMonth) {
        ArrayList<String> strings = new ArrayList<String>();
        for (int i = 1; i <= getDay(curYear, curMonth); i++) {
            if (i < 10) {
                strings.add("0" + i + "日");
            } else {
                strings.add(i + "日");
            }
        }
        return strings;
    }

    /**
     * @param year
     * @param month
     * @return
     */
    private int getDay(int year, int month) {
        int day = 30;
        boolean flag = false;
        switch (year % 4) {
            case 0:
                flag = true;
                break;
            default:
                flag = false;
                break;
        }
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                day = 31;
                break;
            case 2:
                day = flag ? 29 : 28;
                break;
            default:
                day = 30;
                break;
        }
        return day;
    }

    public void setOnTextLinstener(OnTextLinstener listener) {
        this.cardListener = listener;
    }

    /**
     * 密码输入完回调接口
     */
    public interface OnTextLinstener {
        /**
         * 加载更多数据回调方法，由组件自身触发
         */
        void OnDateText(int curYear, String curMonth, String curDate);
    }

    public void showPopupWindow(View view, String date) {
        if (!this.isShowing()) {
            //获取屏幕信息
            if (!CheckUtils.isEmpty(date)) {
                year.setDefault(DateString(date, dateFormat, yearFormat) - 1950);
                month.setDefault(DateString(date, dateFormat, monthFormat) - 1);
                day.refreshData(initDay(DateString(date, dateFormat, yearFormat), DateString(date, dateFormat, monthFormat)));
                day.setDefault(DateString(date, dateFormat, dayFormat) - 1);
            }
            WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
            lp.alpha = 0.6f; // 0.0-1.0
            activity.getWindow().setAttributes(lp);
            // 以下拉方式显示popupwindow
            this.showAtLocation(view,
                    Gravity.BOTTOM, 0, 0);
        }
    }

    /**
     * 年月
     *
     * @return
     */
    private static int DateString(String date, SimpleDateFormat df, SimpleDateFormat cc) {
        int tupeId = 2017;
        try {
            Date strDate = df.parse(date);
            tupeId = Integer.parseInt(cc.format(strDate));
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return tupeId;
    }
}

